﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;

namespace Legend.Fakes.Api
{
    public static class Helpers
    {
        public static void WriteCalls(this IEnumerable<IFakeObjectCall> calls, TextWriter writer)
        {
            Guard.IsNotNull(calls, "calls");
            Guard.IsNotNull(writer, "writer");

            foreach (var call in calls)
            {
                writer.WriteLine(call.GetDescription());
            }
        }

        public static string GetDescription(this IFakeObjectCall call)
        {
            Guard.IsNotNull(call, "call");

            var method = call.Method;

            return "{0}.{1}({2})".FormatInvariant(method.DeclaringType.FullName, method.Name, GetParametersString(call));
        }

        private static string GetParametersString(IFakeObjectCall call)
        {
            var result = new StringBuilder();

            using (var parameters = call.Method.GetParameters().Cast<ParameterInfo>().GetEnumerator())
            using (var arguments = call.Arguments.GetEnumerator())
            {
                while (parameters.MoveNext() && arguments.MoveNext())
                {
                    if (result.Length > 0)
                    {
                        result.Append(", ");
                    }

                    result.AppendFormat("[{0}] {1}", parameters.Current.ParameterType, GetArgumentAsString(arguments.Current));
                }
            }

            return result.ToString();
        }

        private static string GetArgumentAsString(object argument)
        {
            return argument != null ? argument.ToString() : "<NULL>";
        }
    }
}
